import sys
import urllib.request

import bz2
import lzma
import gzip

from abc import ABC, abstractmethod

class Store(ABC):
    # self.os_name

    @abstractmethod
    def search(self, target, filter_arch, filter_search, limit):
        pass

    @abstractmethod
    def autocomplete(self, target, filter_arch, filter_search, limit):
        pass

    @abstractmethod
    def get_pkginfo(self, pkgKey, repo, arch):
        pass


def download(url, filename):
    urllib.request.urlretrieve(url, filename)


def get_decompression_path(filename):
    if filename.endswith('.gz'):
        return filename[:-3]
    if filename.endswith('.bz2'):
        return filename[:-4]
    if filename.endswith('.xz'):
        return filename[:-3]
    else:
        print(f"ERROR: decompression {filename} unsupported", file=sys.stderr)
        return filename


def decompression(filename):
    # 解压缩
    if filename.endswith('.gz'):
        with gzip.open(filename, 'rb') as f_in:
            with open(get_decompression_path(filename), 'wb') as f_out:
                f_out.write(f_in.read())
    if filename.endswith('.bz2'):
        with bz2.open(filename, 'rb') as f_in:
            with open(get_decompression_path(filename), 'wb') as f_out:
                f_out.write(f_in.read())
    if filename.endswith('.xz'):
        with lzma.open(filename, 'rb') as f_in:
            with open(get_decompression_path(filename), 'wb') as f_out:
                f_out.write(f_in.read())
